package com.example.demo.Controller;

import com.example.demo.common.AjaxResult;
import com.example.demo.common.SessionUtil;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ling
 * Date: 2023-12-06
 * Time: 20:03
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public Object reg(String identifyId,String password) {
        if(!StringUtils.hasLength(identifyId) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1,"非法的参数请求");
        }
        User user = userService.getUserByIdentifyId(identifyId);
        if(user != null && user.getId() > 0) {
            return AjaxResult.fail(-2,"用户名已存在");
        }
        int result = userService.register(identifyId,password);
        if(result == 1) {
            return AjaxResult.success(1,"添加成功");
        } else {
            return AjaxResult.fail(-1,"数据添加错误");
        }

    }

    @RequestMapping("/login")
    public Object login(HttpServletRequest request,String identifyId,String password) {
        if(!StringUtils.hasLength(identifyId) || !StringUtils.hasLength(password)) {
            return AjaxResult.fail(-1,"非法的参数请求");
        }
        User user = userService.login(identifyId,password);
        if(user == null || user.getId() <= 0) {
            return AjaxResult.fail(-2,"登录失败");
        } else {
            HttpSession session = request.getSession(true);
            session.setAttribute(SessionUtil.SESSION_USERINFO_KEY,user);
            return AjaxResult.success(1,"添加成功");
        }

    }
}
